<?php

namespace App\Http\Controllers\User\Auth;

use App\Http\Controllers\Controller;
use App\Models\Merchant;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;

class RegisterController extends Controller
{
    public function showRegisterForm()
    {
        return view('user.auth.register');
    }

    public function register(Request $request)
    {
        $this->validateRegister($request);
        $user = $this->create($request->all());
        Merchant::create([
            'user_id' => $user->id,
            'client_secret' => strtoupper(md5(uniqid())),
        ]);
        // $this->guard()->login($user);
        return redirect()->route('user.login');
    }

    public function validateRegister(Request $request)
    {
        $request->validate([
            'username' => 'required|string|unique:users,username|regex:/^[a-zA-Z0-9_]{4,32}$/',
            'email' => 'required|string|email|max:255|unique:users,email',
            'password' => 'required|string|regex:/^[a-zA-Z0-9_.!@#$%^&*-+]{4,32}$/|confirmed',
        ], [
            'username.required'  => '用户名不能为空',
            'username.string'    => '用户名格式错误',
            'username.unique'    => '当前用户名已经存在',
            'username.regex'     => '用户名由4-32位英文字母、数字或下划线组成',
            'email.required'     => '邮箱不能为空',
            'email.string'       => '邮箱格式错误',
            'email.email'        => '邮箱格式错误',
            'email.max'          => '邮箱超过最大长度',
            'email.unique'       => '当前邮箱已经注册',
            'password.required'  => '密码不能为空',
            'password.string'    => '密码格式错误',
            'password.regex'     => '由4-32位英文字母、数字或符号组成',
            'password.confirmed' => '两次密码不一致',
        ]);
    }

    protected function guard()
    {
        return Auth::guard('user');
    }

    protected function create(array $data)
    {
        return User::create([
            'username' => $data['username'],
            'email' => $data['email'],
            'password' => Hash::make($data['password']),
        ]);
    }
}
